# -*- coding: utf-8 -*-
import os

from src.handler.AbstractHandler import AbstractHandler


class CloseComputerHandler(AbstractHandler):
    def _setup_arg(self, subparsers):
        # 添加关闭计算机的子命令
        parser_close = subparsers.add_parser('close', help='关闭电脑')
        parser_close.add_argument('--countdown', '-c', type=int, default=60, help='多少秒之后关机')
        parser_close.set_defaults(func=self.do_process)

        # 添加取消关机的子命令
        parser_cancel = subparsers.add_parser('cancel', help='取消关机')
        parser_cancel.set_defaults(func=self.do_process)

    def _check(self, args):
        """检查参数是否有效"""
        if args.command == 'close':
            return args.countdown >= 0
        elif args.command == 'cancel':
            return True
        return False

    def _process(self, args):
        if args.command == 'close':
            self.do_close(args)
        elif args.command == 'cancel':
            self.do_cancel(args)

    def do_close(self, args):
        countdown = args.countdown
        if countdown > 0:
            self.logger.info(f"Shutting down the computer in {countdown} seconds...")
            os.system(f'shutdown /s /t {countdown}')
        else:
            self.logger.info("Shutting down the computer immediately...")
            os.system('shutdown /s /t 0')

    def do_cancel(self, args):
        self.logger.info("Cancelling scheduled shutdown...")
        os.system('shutdown /a')
